﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Http;
using Microsoft.AspNetCore.Http;
using my.abp.Domain.Shared.Entities;
using System.Diagnostics;
using my.abp.Domain.IManagers.User;

namespace my.abp.Domain.Authorization
{
	/// <summary>
	/// 全局 操作权限判断 过滤器
	/// </summary>
	internal class PermissionGlobalAttribute : ActionFilterAttribute, ITransientDependency
	{
		private readonly IPermissionHandler _permissionHandler;
		private Framework.AspNetCore.User.CurrentUser _currentUser { get; set; }

		private ISysUserManager _sysUserManager;

		public PermissionGlobalAttribute(ISysUserManager sysUserManager, Framework.AspNetCore.User.CurrentUser currentUser, IPermissionHandler permissionHandler)
		{
			_currentUser = currentUser;
			_sysUserManager = sysUserManager;
			_permissionHandler = permissionHandler;
		}

		public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
		{
			var controllerName = context.RouteData.Values["controller"] + "/";

			var result = await _permissionHandler.IsPass();

			if (!result)
			{
				var model = new RemoteServiceErrorInfo()
				{
					Code = "403",
					Message = $"您无权限访问,请联系管理员申请",
					Details = $"您无权限访问该接口-{context.HttpContext.Request.Path.Value}",
				};

				var content = new ObjectResult(new { error = model })
				{
					StatusCode = 403
				};
				context.Result = content;
				return;
			}

			await next();
		}
	}
}
